import json
import os
import time

from .leetcode_operation import LeetCodeOperation


class GetStudyPlanCatalogs(LeetCodeOperation):
    def __init__(self, requests_manager, base_url="https://leetcode.cn", **params):
        super().__init__(requests_manager, base_url)
        self.params = params.get('params')
        self.filename="GetStudyPlanCatalogs.json"
        self.endpoint = 'graphql'

    def generate_payload(self):
        query_string = "\n    query GetStudyPlanCatalogs {\n  studyPlanV2Catalogs {\n    name\n    recommendedStudyPlans\n    slug\n  }\n}\n    "
        return {
            "query": query_string,
            "variables": self.params,
            "operationName": "GetStudyPlanCatalogs"
        }
        
    def parse_graphql_data(self, data):
        data = data.get('data', {}).get('studyPlanV2Catalogs', {})
        return data
    
    # Execute Method
    def execute(self):
        if os.path.exists(os.path.join(self.directory, self.filename)):
            return 
        data = self.fetch_data(self.endpoint, method='POST')
        data = self.parse_graphql_data(data)
        self.save_json(data, self.filename)